import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'index.dart';

/// AI 页面视图
/// 
/// 🎯 核心功能：
/// 1. 显示 AI 智能搜索 WebView
/// 2. 透明状态栏样式
/// 3. 加载状态和错误处理
/// 4. 长按语音输入功能
class AiPage extends GetView<AiController> {
  const AiPage({super.key});

  /// 构建主视图
  Widget _buildView() {
    return Stack(
      children: [
        // WebView
        WebViewWidget(controller: controller.webViewController),
        
        // 🎤 语音录音界面覆盖层
        _buildVoiceOverlay(),
        
        // 加载进度指示器
        Obx(() => controller.isLoading.value
          ? Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.red.shade500),
                  ),
                  const SizedBox(height: 16),
                  Obx(() => Text('加载中 ${controller.loadingProgress.value}%')),
                ],
              ),
            )
          : const SizedBox.shrink()
        ),
        
        // 错误显示
        Obx(() => controller.hasError.value
          ? Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.error_outline, size: 48, color: Colors.red),
                  const SizedBox(height: 16),
                  const Text(
                    '页面加载失败', 
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
                  ),
                  const SizedBox(height: 8),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 24),
                    child: Text(
                      controller.errorMessage.value.isNotEmpty 
                          ? controller.errorMessage.value 
                          : '请检查资源文件路径或网络连接',
                      style: TextStyle(color: Colors.grey[600]),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  const SizedBox(height: 24),
                  TextButton(
                    onPressed: controller.reload,
                    style: TextButton.styleFrom(
                      backgroundColor: Colors.red.shade500,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                    ),
                    child: const Text('重新加载'),
                  ),
                ],
              ),
            )
          : const SizedBox.shrink()
        ),
      ],
    );
  }

  /// 🎤 构建语音录音覆盖层
  Widget _buildVoiceOverlay() {
    return Obx(() {
      // 只有在录音或处理时才显示覆盖层
      final showOverlay = controller.isVoiceRecording.value || controller.isVoiceProcessing.value;
      
      if (!showOverlay) {
        return const SizedBox.shrink();
      }

      // 🔧 使用AnimatedSwitcher避免跳动
      return AnimatedSwitcher(
        duration: const Duration(milliseconds: 200),
        child: Container(
          key: ValueKey('voice_overlay_${controller.isVoiceRecording.value ? 'recording' : 'processing'}'),
          color: Colors.black.withOpacity(0.8),
          child: Center(
            child: Container(
              width: 280,
              height: 280,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 20,
                    spreadRadius: 5,
                  ),
                ],
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // 🔧 使用AnimatedSwitcher平滑切换动画
                  AnimatedSwitcher(
                    duration: const Duration(milliseconds: 300),
                    child: controller.isVoiceRecording.value
                        ? _buildRecordingContent()
                        : _buildProcessingContent(),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    });
  }

  /// 🎤 构建录音内容
  Widget _buildRecordingContent() {
    return Column(
      key: const ValueKey('recording'),
      mainAxisSize: MainAxisSize.min,
      children: [
        _buildRecordingIcon(),
        const SizedBox(height: 20),
        const Text(
          '正在录音...',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.red,
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          '松手结束录音',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  /// 🎤 构建处理内容
  Widget _buildProcessingContent() {
    return Column(
      key: const ValueKey('processing'),
      mainAxisSize: MainAxisSize.min,
      children: [
        _buildProcessingAnimation(),
        const SizedBox(height: 20),
        const Text(
          '正在处理语音...',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.blue,
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          'AI正在识别您的语音内容',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  /// 🎤 构建录音图标（脉动动画）
  Widget _buildRecordingIcon() {
    return const _PulsingIcon(
      icon: Icons.mic,
      color: Colors.red,
      size: 120,
    );
  }

  /// 🎤 构建处理动画（旋转动画）
  Widget _buildProcessingAnimation() {
    return const _RotatingIcon(
      icon: Icons.psychology,
      color: Colors.blue,
      size: 120,
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏透明
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    
    return Scaffold(
      backgroundColor: const Color(0xFFE33641), // 红色背景
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        toolbarHeight: 0, // 将 AppBar 高度设为 0，只保留状态栏区域
        automaticallyImplyLeading: false,
        systemOverlayStyle: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.light,
          statusBarBrightness: Brightness.dark, // iOS
        ),
      ),
      body: SafeArea(
        top: false, // 允许内容延伸到状态栏
        child: _buildView(),
      ),
    );
  }
}

// ========== 🎤 动画组件 ==========

/// 🎤 脉动动画图标组件
class _PulsingIcon extends StatefulWidget {
  final IconData icon;
  final Color color;
  final double size;

  const _PulsingIcon({
    required this.icon,
    required this.color,
    required this.size,
  });

  @override
  _PulsingIconState createState() => _PulsingIconState();
}

class _PulsingIconState extends State<_PulsingIcon>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  bool _isDisposed = false;

  @override
  void initState() {
    super.initState();
    
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );
    
    _animation = Tween<double>(
      begin: 0.8,
      end: 1.2,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    ));
    
    // 🔧 延迟启动动画，避免初始化冲突
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_isDisposed && mounted) {
        _controller.repeat(reverse: true);
      }
    });
  }

  @override
  void dispose() {
    _isDisposed = true;
    _controller.stop();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isDisposed) {
      return const SizedBox.shrink();
    }
    
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Transform.scale(
          scale: _animation.value,
          child: Container(
            width: widget.size,
            height: widget.size,
            decoration: BoxDecoration(
              color: widget.color.withOpacity(0.1),
              shape: BoxShape.circle,
              border: Border.all(
                color: widget.color.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: Icon(
              widget.icon,
              size: widget.size * 0.5,
              color: widget.color,
            ),
          ),
        );
      },
    );
  }
}

/// 🎤 旋转动画图标组件
class _RotatingIcon extends StatefulWidget {
  final IconData icon;
  final Color color;
  final double size;

  const _RotatingIcon({
    required this.icon,
    required this.color,
    required this.size,
  });

  @override
  _RotatingIconState createState() => _RotatingIconState();
}

class _RotatingIconState extends State<_RotatingIcon>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  bool _isDisposed = false;

  @override
  void initState() {
    super.initState();
    
    _controller = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );
    
    _animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.linear,
    ));
    
    // 🔧 延迟启动动画，避免初始化冲突
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_isDisposed && mounted) {
        _controller.repeat();
      }
    });
  }

  @override
  void dispose() {
    _isDisposed = true;
    _controller.stop();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isDisposed) {
      return const SizedBox.shrink();
    }
    
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Transform.rotate(
          angle: _animation.value * 6.28318, // 2 * pi
          child: Container(
            width: widget.size,
            height: widget.size,
            decoration: BoxDecoration(
              color: widget.color.withOpacity(0.1),
              shape: BoxShape.circle,
              border: Border.all(
                color: widget.color.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: Icon(
              widget.icon,
              size: widget.size * 0.5,
              color: widget.color,
            ),
          ),
        );
      },
    );
  }
}
